/************************************************************************************

Class Name	:	Main.class
Description	:	Used to implement all the algorithms including ordinary, trigonometric and matrices.
Author		:	W.S.V.K.Koggala <v.koggala@gmail.com>

*************************************************************************************/

package com.androidcal.calculator;

import java.text.DecimalFormat;
//import org.nfunk.jep.*;
//import org.lsmp.djep.xjep.*;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.Stack;
import java.util.StringTokenizer;



import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
//import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
//import android.view.View.OnFocusChangeListener;

/**
 * 
 */
public class Main extends Activity{
	GridView keypadGrid;
	KeypadAdapter keypadAdapter;
	TextView userInput;
	boolean resetInput= false; 
	private boolean DEBUG=true;
	private boolean INFO=true;
	private boolean ET1=false;
	private boolean ET2=false;
	private int n=4;
	private static NumberFormat nf;
	private static int decimals = 3;
	private static int max=100;
	private EditText userMat1,userMat2,userMat3;
	private int iDF = 0;
	
	Stack<String> inputS;
	Stack<String> operationS;
	boolean hasFinalResult=false;
	TextView opText;
	String currentInput;
	String decimalSep;
	double memoryValue=Double.NaN;
	double value;
	String []res=new String[20];
	//String result;
	double result = Double.NaN;
	int q=0;
	String [] evalResult1;
	double[]roots;
	

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        DecimalFormat currencyFormatter = (DecimalFormat)NumberFormat.getInstance();
        char decimalSeperator = currencyFormatter.getDecimalFormatSymbols().getDecimalSeparator();
        decimalSep = Character.toString(decimalSeperator);


        setContentView(R.layout.main);
        
        inputS = new Stack<String>();
        operationS = new Stack<String>();


        
        keypadGrid = (GridView) findViewById(R.id.buttons);
        
        userInput = (TextView) findViewById(R.id.InputS);
        userInput.setText("0");
        
      
        
        userMat1 = (EditText) findViewById(R.id.EditText01);
        userMat1.setText("");
        userMat2 = (EditText) findViewById(R.id.EditText02);
        userMat2.setText("");
        userMat3 = (EditText) findViewById(R.id.EditText03);
        userMat3.setText("");
        opText = (TextView) findViewById(R.id.opT);
        
        
        nf = NumberFormat.getInstance();
		nf.setMinimumFractionDigits(1);
		nf.setMaximumFractionDigits(decimals);





        // Create Keypad Adapter
        keypadAdapter = new KeypadAdapter(this);
        
        // Set adapter of the keypad grid
        keypadGrid.setAdapter(keypadAdapter);
        keypadAdapter.setOnButtonClickListener(new OnClickListener(){
        	@Override
        	public void onClick(View v){
        		Button btn = (Button) v;
        		KeypadButton keypadButton = (KeypadButton) btn.getTag();
        		CalculationLogic(keypadButton);



        	}
        });
        
        
        keypadGrid.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
            }
        });


    }
    
    /**
     * 
     * @param keypadButton 
     */
    private void CalculationLogic(KeypadButton keypadButton){
    	String text = keypadButton.getText().toString();
		String currentInput = userInput.getText().toString();

		int currentInputLen = currentInput.length();
		String evalResult = null;
		//double userInputValue = Double.NaN;

		switch (keypadButton) {
		case DELETE:                  // Backspace numbers
		//	if (resetInput)          
			//	return;

			int endIndex = currentInputLen - 1;

			// There is one character at input so reset input to 0
			if (endIndex < 1) {
				userInput.setText("0");
			}
			// delete last character of the input text
			else {
				userInput.setText(currentInput.subSequence(0, endIndex));
			}
			break;
		case AC:
			userInput.setText("0");
			userMat1.setText("");
			userMat2.setText("");
			userMat3.setText("");
			clearStacks();
			break;
		case SIGN: // Handle -/+ sign
			// if current input has text and is different than initial value 0
			if (currentInputLen > 0 && currentInput != "0") {
				// Already has (-) sign. Remove that sign
				if (currentInput.charAt(0) == '-') {
					userInput.setText(currentInput.subSequence(1,currentInputLen));
				}
				// add (-) sign
				else {
					userInput.setText("-" + currentInput.toString());
				}
			}
			break;
		case DOT: // Handle decimal separator
			if (hasFinalResult || resetInput) {
				userInput.setText("0" + decimalSep);
				hasFinalResult = false;
				resetInput = false;
			} else if (currentInput.contains("."))
				return;
			else
				userInput.append(decimalSep);
			break;
			//Handle division, addition, subtraction, multiplication and powers
	    case DIVIDE:
		case PLUS:
		case MINUS:
		case MULTIPLY:
		case POWER:
			if (resetInput) {
			    inputS.pop();
				operationS.pop();
			} else {
				if (currentInput.charAt(0) == '-') {
					inputS.add("(" + currentInput + ")");
				} else {
					inputS.add(currentInput);
				}
				operationS.add(currentInput);
			}

			inputS.add(text);
			operationS.add(text);

			AddOpStack();
			evalResult = evaluateResult(false);
			if (evalResult != null)
				userInput.setText(evalResult);

			resetInput = true;
			break;
		case EQUALS:
			if (operationS.size() == 0)
				break;

			operationS.add(currentInput);
		
			evalResult = evaluateResult(true);
			if (evalResult != null) {
				clearStacks();
				userInput.setText(evalResult);
				resetInput = false;
				hasFinalResult = true;
			}

			break;
			//calculate the square root of numbers 
		case SQRT:
			if (currentInput.charAt(0) == '-') {//if number is less than 0
				userInput.setText("Math Error");
			}else{
				double value= Double.parseDouble(userInput.getText().toString());
				double result=Math.sqrt(value);
				String res=doubleToString(result);
				userInput.setText(res);
			}
		break;
		case CBRT:
			if (currentInput.charAt(0) == '-') {//if number is less than 0
				userInput.setText("Math Error");
			}else{
				double value= Double.parseDouble(userInput.getText().toString());
				double result=Math.cbrt(value);
				String res=doubleToString(result);
				userInput.setText(res);
			}
			break;
		case SQUARE:
			double value= Double.parseDouble(userInput.getText().toString());
			double result=value*value;
			String res=doubleToString(result);
			userInput.setText(res);
			break;
		case PI:
			userInput.setText(Double.toString(Math.PI));
			break;
			//calculate sin values in radian
		case SIN:
		    value=Double.parseDouble(userInput.getText().toString());
		    result=Math.sin(value);
		    res=doubleToString(result);
			userInput.setText(res);
			break;
			//Calculate sin inverse values in radian
		case ASIN:
			value=Double.parseDouble(userInput.getText().toString());
			result=Math.asin(value);
		    res=doubleToString(result);
			userInput.setText(res);
			break;
			//calculate cos values in radian
		case COS:
			double value1=Double.parseDouble(userInput.getText().toString());
			double result1=Math.cos(value1);
			String res1=doubleToString(result1);
			userInput.setText(res1);
			break;
			//get cos inverse values
		case ACOS:
			value=Double.parseDouble(userInput.getText().toString());
			result=Math.acos(value);
		    res=doubleToString(result);
			userInput.setText(res);
			break;
			//calculate tan values in radian
		case TAN:
			double value2=Double.parseDouble(userInput.getText().toString());
			double result2=Math.tan(value2);
			String res2=doubleToString(result2);
			userInput.setText(res2);
			break;
			//get tan inverse values
		case ATAN:
			value=Double.parseDouble(userInput.getText().toString());
			result=Math.atan(value);
		    res=doubleToString(result);
			userInput.setText(res);
			break;
			//calculate sinh values in radian
		case SINH:
			double value3=Double.parseDouble(userInput.getText().toString());
			double result3=Math.sinh(value3);
			String res3=doubleToString(result3);
			userInput.setText(res3);
			break;
			//calculate cosh values in radian
		case COSH:
			double value4=Double.parseDouble(userInput.getText().toString());
			double result4=Math.cosh(value4);
			String res4=doubleToString(result4);
			userInput.setText(res4);
			break;
			//calculate tanh values in radian
		case TANH:
			double value5=Double.parseDouble(userInput.getText().toString());
			double result5=Math.tanh(value5);
			String res5=doubleToString(result5);
			userInput.setText(res5);
			break;
			//convert radian to degrees
		case DEGREE:
			double value6=Double.parseDouble(userInput.getText().toString());
			double result6=Math.toDegrees(value6);
			String res6=doubleToString(result6);
			userInput.setText(res6);
			break;
			//convert degrees to radian
		case RADIAN:
			double value7=Double.parseDouble(userInput.getText().toString());
			double result7=Math.toRadians(value7);
			String res7=doubleToString(result7);
			userInput.setText(res7);
			break;
			//calculate log values for the base 10
		case LOG:
			value=Double.parseDouble(userInput.getText().toString());
			result=Math.log10(value);
			res=doubleToString(result);
			userInput.setText(res);
			break;
			//calculate log values for the base e
		case LN:
			value=Double.parseDouble(userInput.getText().toString());
			result=Math.log(value);
			res=doubleToString(result);
			userInput.setText(res);
			break;
			//get e to the power values 
		case E:
			value=Double.parseDouble(userInput.getText().toString());
			result=Math.exp(value);
			res=doubleToString(result);
			userInput.setText(res);
			break;
		case SOLVE:
			//while(true){
			try{
			String eq = userMat1.getText().toString();
			StringTokenizer tokenizer=new StringTokenizer(eq);
			if (tokenizer.countTokens()!=3){
			    System.out.println("Invalid coefficients: expected 3 coefficients");
			 //   continue;
			}
			int a=0;int b=0;int c=0;
			try{
			    a=Integer.parseInt(tokenizer.nextToken());
			    b=Integer.parseInt(tokenizer.nextToken());
			    c=Integer.parseInt(tokenizer.nextToken());
			}
			catch(NumberFormatException e){
			    System.out.println("coeffecients must be integers");
			 //   continue;
			}
			double[]roots=solve(a,b,c);
			if (roots==null)
			    userMat2.setText("All x are solutions");
			else if (roots.length==0)
				 userMat2.setText("No solutions");
			else if (roots.length==1)
				 userMat2.setText("Solution is: x= "+roots[0]);
			else if (roots.length==2)
				 userInput.setText("Solutions are: X= "+roots[0]+" or X= "+roots[1]);
			} catch (Exception e) {
				userInput.setText("Error");
			}
			
			break;
		case EQUATIONS:
			userInput.setText("Enter a b c using spaces in mA.");
			opText.setText("Press calc button to solve.");
			break;
		case HELP:
			startActivity(new Intent(getApplicationContext(), Help.class));
            //finish(); 
			break;
			//convert decimal to hexadecimal
		case HEXADECIMAL:
		   // currentInput = userInput.getText().toString();
			if(currentInput.contains(".")){
				userInput.setText("Required Integer");
			}else{
		    int valueHex=Integer.parseInt(userInput.getText().toString());
		    userInput.setText(Integer.toHexString(valueHex));
			}
			break;	
			//convert decimal to octal
		case OCTAL:
			//currentInput = userInput.getText().toString();
			if(currentInput.contains(".")){
				userInput.setText("Required Integer");
			}else{
			int valueOct=Integer.parseInt(userInput.getText().toString());
			userInput.setText(Integer.toOctalString(valueOct));
			}
			break;
			//convert decimal to binary
		case BINARY:
			currentInput = userInput.getText().toString();
			if(currentInput.contains(".")){
				userInput.setText("Required Integer");
			}else{
			int valueBin=Integer.parseInt(userInput.getText().toString());
			userInput.setText(Integer.toBinaryString(valueBin));
			}
			break;
			//putting a space between numbers 
		case SPACE:
			if(ET1)
			userMat1.append(" ");
			else if(ET2)
				userMat2.append(" ");
			break;
			//Add two matirices
		case MATRIXADD:
			try {
				DisplayMatrix(AddMatrix(ReadInMatrix(userMat1),
						ReadInMatrix(userMat2)), userMat3);
			} catch (Exception e) {
			System.err.println("Error: " + e);
			}
			
			break;
			//Multiply two matrices
		case MATMUL:
			try {
				DisplayMatrix(MultiplyMatrix(
						ReadInMatrixNotSquare(userMat1),
						ReadInMatrixNotSquare(userMat2)), userMat3);
			} catch (Exception e) {
				System.err.println("Error: " + e);
			}
			break;
		case INVERSE:
			try {
				DisplayMatrix(Inverse(ReadInMatrix(userMat1)), userMat3);
			} catch (Exception e) {
				System.err.println("Error: " + e);
			}
			break;
		case DETERMINANT:
			try {
				userMat3.setText("Determinant A: "
						+ nf.format(Determinant(ReadInMatrix(userMat1))));
			} catch (Exception e) {
				userInput.setText("Error");
			}
			break;
		case TRANSPOSE:
			try {
				DisplayMatrix(Transpose(ReadInMatrixNotSquare(userMat1)), userMat3);
			} catch (Exception e) {
				userInput.setText("Error");
			}
			break;
		case ADJOINT:
			try {
				DisplayMatrix(Adjoint(ReadInMatrix(userMat1)), userMat3);
			} catch (Exception e) {
				System.err.println("Error: " + e);
			}
			break;
		case MATB:
			ET1=false;
			ET2=true;
			userMat1.setCursorVisible(false);
		//	userMat1.setEnabled(false);
			//userMat2.setEnabled(true);
			userMat2.setCursorVisible(true);
			//userMat2.setText("4");
			//userMat1.setText(userMat1.getText().toString() + "\n");
			//userMat1.setSelection(userMat1.getText().length());
			break;
		case MATRIX:
			userInput.setText("Welcome to matrix menu");
			break;
		case MATA:
			ET2=false;
			ET1=true;
			userMat2.setCursorVisible(false);
			userMat1.setCursorVisible(true);
			break;
		case BASIC:
			userInput.setText("Welcome to ordinary calculations menu");
			userMat1.setCursorVisible(false);
			userMat2.setCursorVisible(false);
			ET2=false;
			ET1=false;
		case ENT:
			if(ET1){
			userMat1.setText(userMat1.getText().toString() + "\n");
			userMat1.setSelection(userMat1.getText().length());
			}else if(ET2){
				userMat2.setText(userMat2.getText().toString() + "\n");
				userMat2.setSelection(userMat2.getText().length());
			}
			break;
			//break;
		default:
			if(ET1==false&&ET2==false){
			if (Character.isDigit(text.charAt(0))) {
				if (currentInput.equals("0") || resetInput || hasFinalResult) {
					userInput.setText(text);
					resetInput = false;
					hasFinalResult = false;
				} else {
					userInput.append(text);
					resetInput = false;
				}

			}
			}else if(ET1){
				if (Character.isDigit(text.charAt(0))) {
					if ( resetInput || hasFinalResult) {
						userMat1.setText(text);
						resetInput = false;
						hasFinalResult = false;
					} else {
						userMat1.append(text);
						resetInput = false;
					}

				}
			}else if(ET2){
				if (Character.isDigit(text.charAt(0))) {
					if ( resetInput || hasFinalResult) {
						userMat2.setText(text);
						resetInput = false;
						hasFinalResult = false;
					} else {
						userMat2.append(text);
						resetInput = false;
					}

				}
			}
			break;

		}

	}

	private void clearStacks() {
		inputS.clear();
		operationS.clear();
		opText.setText("");
	}

	private void AddOpStack() {
		Iterator<String> iterator = inputS.iterator();
		StringBuilder stringb = new StringBuilder();

		while (iterator.hasNext()) {          //while there are more elements in the iterator
			CharSequence iValue = iterator.next();
			stringb.append(iValue);

		}

		opText.setText(stringb.toString());
	}
//calculate division, addition, multiplication, subtraction and powers
	private String evaluateResult(boolean requestedByUser) {
		if ((!requestedByUser && operationS.size() != 4)
				|| (requestedByUser && operationS.size() != 3))
			return null;

		String left = operationS.get(0);
		String operator = operationS.get(1);
		String right = operationS.get(2);
		String tmp = null;
		if (!requestedByUser)
			tmp = operationS.get(3);

		double leftVal = Double.parseDouble(left.toString());
		double rightVal = Double.parseDouble(right.toString());
	

		if (operator.equals(KeypadButton.DIVIDE.getText())&rightVal!=0) {
			result = leftVal / rightVal;
		}else if(rightVal==0){
				userInput.setText("Math Error");
		} else if (operator.equals(KeypadButton.MULTIPLY.getText())) {
			result = leftVal * rightVal;
		} else if (operator.equals(KeypadButton.PLUS.getText())) {
			result = leftVal + rightVal;
		} else if (operator.equals(KeypadButton.MINUS.getText())) {
			result = leftVal - rightVal;
		} else if (operator.equals(KeypadButton.POWER.getText())){
			result=Math.pow(leftVal, rightVal);
		}

		String resultStr = doubleToString(result);
		if (resultStr == null)
			return null;

		operationS.clear();
		if (!requestedByUser) {
			operationS.add(resultStr);
			operationS.add(tmp);
		}

		return resultStr;
	}
		private String doubleToString(double value) {
		if (Double.isNaN(value))
			return null;

		long longVal = (long) value;
		if (longVal == value)
			return Long.toString(longVal);
		else
			return Double.toString(value);

	}
	public float[][] AddMatrix(float[][] a, float[][] b) throws Exception {
		int tms = a.length;
		int tmsB = b.length;
		if (tms != tmsB) {
			//statusBar.setText("Matrix Size Mismatch");
		}

		float matrix[][] = new float[tms][tms];

		for (int i = 0; i < tms; i++)
			for (int j = 0; j < tms; j++) {
				matrix[i][j] = a[i][j] + b[i][j];
			}

		return matrix;
	}
	public float[][] MultiplyMatrix(float[][] a, float[][] b) throws Exception {

		if(a[0].length != b.length)
			throw new Exception("Matrices incompatible for multiplication");
		float matrix[][] = new float[a.length][b[0].length];

		for (int i = 0; i < a.length; i++)
			for (int j = 0; j < b[i].length; j++)
				matrix[i][j] = 0;

		//cycle through answer matrix
		for(int i = 0; i < matrix.length; i++){
			for(int j = 0; j < matrix[i].length; j++){
				matrix[i][j] = calculateRowColumnProduct(a,i,b,j);
			}
		}
		return matrix;
	}
	public float calculateRowColumnProduct(float[][] A, int row, float[][] B, int col){
		float product = 0;
		for(int i = 0; i < A[row].length; i++)
			product +=A[row][i]*B[i][col];
		return product;
	}
	//Calculate the inverse of a matrix
	public float[][] Inverse(float[][] a) throws Exception {
		// Formula used to Calculate Inverse:
		// inv(A) = 1/det(A) * adj(A)
		int tms = a.length;

		float m[][] = new float[tms][tms];
		float mm[][] = Adjoint(a);

		float det = Determinant(a);
		float dd = 0;

		if (det == 0) {
			userInput.setText("Determinant Equals 0, Not Invertible.");
		} else {
			dd = 1 / det;
		}

		for (int i = 0; i < tms; i++)
			for (int j = 0; j < tms; j++) {
				m[i][j] = dd * mm[i][j];
			}

		return m;
	}
	public float Determinant(float[][] matrix) {
		/*if (INFO) {
			System.out.println("Getting Determinant...");
		}*/
		int tms = matrix.length;

		float det = 1;

		matrix = UpperTriangle(matrix);

		for (int i = 0; i < tms; i++) {
			det = det * matrix[i][i];
		} // multiply down diagonal

		det = det * iDF; // adjust w/ determinant factor

		if (INFO) {
			System.out.println("Determinant: " + det);
		}
		return det;
	}
	//Calculate the adjoint of a matrix
	public float[][] Adjoint(float[][] a) throws Exception {
		int tms = a.length;

		float m[][] = new float[tms][tms];

		int ii, jj, ia, ja;
		float det;

		for (int i = 0; i < tms; i++)
			for (int j = 0; j < tms; j++) {
				ia = ja = 0;

				float ap[][] = new float[tms - 1][tms - 1];

				for (ii = 0; ii < tms; ii++) {
					for (jj = 0; jj < tms; jj++) {

						if ((ii != i) && (jj != j)) {
							ap[ia][ja] = a[ii][jj];
							ja++;
						}

					}
					if ((ii != i) && (jj != j)) {
						ia++;
					}
					ja = 0;
				}

				det = Determinant(ap);
				m[i][j] = (float) Math.pow(-1, i + j) * det;
			}

		m = Transpose(m);

		return m;
	}
	//Calculate the transpose of a matrix
	public float[][] Transpose(float[][] a) {
		if (INFO) {
			System.out.println("Performing Transpose...");
		}

		float m[][] = new float[a[0].length][a.length];

		for (int i = 0; i < a.length; i++)
			for (int j = 0; j < a[i].length; j++)
				m[j][i] = a[i][j];
		return m;
	}



	public float[][] ReadInMatrix(TextView TextView01) throws Exception {

		/* == Parse Text Area == */
		String rawtext = TextView01.getText().toString();
		String val = "";
		int i = 0;
		int j = 0;
		int[] rsize = new int[max];

		/* == Determine Matrix Size/Valid == */
		StringTokenizer ts = new StringTokenizer(rawtext, "\n");
		while (ts.hasMoreTokens()) {
			StringTokenizer ts2 = new StringTokenizer(ts.nextToken());
			while (ts2.hasMoreTokens()) {
				ts2.nextToken();
				j++;
			}
			rsize[i] = j;
			i++;
			j = 0;
		}
		//statusBar.setText("Matrix Size: " + i);
		if ((DEBUG) || (INFO)) {
			System.out.println("Matrix Size: " + i);
		}

		for (int c = 0; c < i; c++) {
			if (DEBUG) {
				System.out.println("i=" + i + "  j=" + rsize[c] + "   Column: "
						+ c);
			}

			if (rsize[c] != i) {
				userInput.setText("Invalid Matrix Entered. Size Mismatch.");
				throw new Exception("Invalid Matrix Entered. Size Mismatch.");
			}
		}
		/* == set matrix size == */
		n = i;

		float matrix[][] = new float[n][n];
		i = j = 0;
		val = "";

		/* == Do the actual parsing of the text now == */
		StringTokenizer st = new StringTokenizer(rawtext, "\n");
		while (st.hasMoreTokens()) {
			StringTokenizer st2 = new StringTokenizer(st.nextToken());
			while (st2.hasMoreTokens()) {
				val = st2.nextToken();
				try {
					matrix[i][j] = Float.valueOf(val).floatValue();
				} catch (Exception exception) {
					userInput.setText("Invalid Number Format");
				}
				j++;
			}
			i++;
			j = 0;
		}

	/*	if (DEBUG) {
			System.out.println("Matrix Read::");
			for (i = 0; i < n; i++) {
				for (j = 0; j < n; j++) {
					System.out.print("m[" + i + "][" + j + "] = "
							+ matrix[i][j] + "   ");
				}
				System.out.println();
			}
		}*/

		return matrix;
	}

	public float[][] ReadInMatrixNotSquare(TextView TextView01)
			throws Exception {
		if (DEBUG) {
			System.out.println("Reading In Matrix");
		}

		/* == Parse Text Area == */
		String rawtext = TextView01.getText().toString();

		/* == Determine Matrix Size/Valid == */
		StringTokenizer ts = new StringTokenizer(rawtext, "\n");

		if (DEBUG)
			System.out.println("Rows: " + ts.countTokens());

		float matrix[][] = new float[ts.countTokens()][];

		StringTokenizer st2;
		int row = 0;
		int col = 0;
		//making sure rows are same length
		int last = -5;
		int curr = -5;
		while (ts.hasMoreTokens()) {
			st2 = new StringTokenizer(ts.nextToken(), " ");
			last = curr;
			curr = st2.countTokens();
			if(last != -5 && curr!= last)
				throw new Exception("Rows not of equal length");
			if (DEBUG)
				System.out.println("Cols: " + st2.countTokens());
			matrix[row] = new float[st2.countTokens()];
			while (st2.hasMoreElements()) {
				matrix[row][col++] = Float.parseFloat(st2.nextToken());
			}
			row++;
			col = 0;
		}
		System.out.println();
		return matrix;
	}
	public void DisplayMatrix(float[][] matrix, TextView ta) {

		/* == TODO: Better Formatting of Resultant Matrix == */

		if (DEBUG) {
			System.out.println("Displaying Matrix");
		}

		String rstr = "";
		String dv = "";

		for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix[i].length; j++) {
				dv = nf.format(matrix[i][j]);
				rstr = rstr.concat(dv + "  ");
			}

			rstr = rstr.concat("\n");
		}

		ta.setText(rstr);
	}
	 public double[] solve(int a,int b, int c){
			if (a==0&&b==0&&c==0)
			    roots=null;
			else if (a==0&&b==0)
			    roots=new double[0];
			else if (a==0)
			    roots=new double[]{-c/b};
			else{
			    double discriminant= b*b-4*a*c;
			    if (discriminant<0)
				roots=new double[0];
			    else if (discriminant==0)
				roots=new double[]{ (-b + Math.sqrt(discriminant))/(2*a)};
			    else
				roots=new double[]{
				    (-b + Math.sqrt(discriminant))/(2*a),
				    (-b - Math.sqrt(discriminant))/(2*a)
				};
			}
			return roots;
		    }
	 	//Making an upper triangular matrix
	public float[][] UpperTriangle(float[][] m) {
		/*if (INFO) {
			System.out.println("Converting to Upper Triangle...");
		}*/

		float f1 = 0;
		float temp = 0;
		int tms = m.length; // get This Matrix Size 
						
		int v = 1;

		iDF = 1;

		for (int col = 0; col < tms - 1; col++) {
			for (int row = col + 1; row < tms; row++) {
				v = 1;

				 while (m[col][col] == 0) // check if 0 in diagonal
				{ // if so switch until not
					if (col + v >= tms) // check if switched all rows
					{
						iDF = 0;
						break ;
					} else {
						for (int c = 0; c < tms; c++) {
							temp = m[col][c];
							m[col][c] = m[col + v][c]; // switch rows
							m[col + v][c] = temp;
						}
						v++; // count row switchs
						iDF = iDF * -1; // each switch changes determinant
										// factor
					}
				}

				if (m[col][col] != 0) {

					try {
						f1 = (-1) * m[row][col] / m[col][col];
						for (int i = col; i < tms; i++) {
							m[row][i] = f1 * m[col][i] + m[row][i];
						}
					} catch (Exception e) {
						System.out.println("Still Here!!!");
					}

				}

			}
		}

		return m;
	}
	



	
	/*private double tryParseUserInput() {
		String inputStr = userInput.getText().toString();
		double result = Double.NaN;
		try {
			result = Double.parseDouble(inputStr);

		} catch (NumberFormatException nfe) {}
		return result;


    }*/
}